package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.auth;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.log.SysLogBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.SysLoginlogVo;
import com.xiaoxu.intranetweb.util.SzResult;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户登录业务层
 *
 * @author xiaoxu
 * @version 1.0
 * @date 2023/1/13 15:00
 * @since 1.0
 */
@Component
public class LoginBu {
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private SysLogBu sysLogBu;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private ISysUserPlantConnService iSysUserPlantConnService;
    @Autowired
    private ITPlantsService iTPlantsService;
    @Autowired
    private ISysLoginlogService iSysLoginlogService;

    public SzResult login(String username, String password, String ip, String plantId) throws Exception {
        SzResult szResult = new SzResult();
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
//        验证用户名或者手机号
        //queryWrapper.eq("USER_NAME", username).or().eq("PHONE", username);
        queryWrapper.and(i -> i.eq("USER_NAME", username).or().eq("PHONE", username));
        queryWrapper.eq("PWD_DETAIL", password);
        queryWrapper.eq("DEL_FLAG", 0);
        SysUser sysUser = iSysUserService.getOne(queryWrapper);
        if (sysUser == null) {
            szResult.setCode(200);
            szResult.setMsg("error");
            szResult.setResult("用户名或密码错误");
            return szResult;
        }
        if (sysUser.getEnableFlag() == 0) {
            szResult.setCode(200);
            szResult.setMsg("error");
            szResult.setResult("该用户已被冻结");
            // sysLogBu.logRecord("网页端用户登录",username,"登录失败,该用户已被冻结->ip:"+ip,plantId);
            //sysLogBu.loginRecord(sysUser.getId(),ip);
            return szResult;
        }
        if (sysUser.getIfWeb() == 0) {
            return SzResult.Error("该用户不是网页端用户");
        }
        if (sysUser.getDelFlag() == 0) {
//            登录
            StpUtil.login(sysUser.getId());
            Map<String, Object> loginInfo = new HashMap<>();
            loginInfo.put("token", StpUtil.getTokenValue());
            QueryWrapper<SysUserPlantConn> queryWrapper8 = new QueryWrapper<>();
            queryWrapper8.eq("USER_ID", sysUser.getId());
            List<SysUserPlantConn> userPlantConnList = iSysUserPlantConnService.list(queryWrapper8);
            List<Map> plantNameList = new ArrayList<>();
            for (SysUserPlantConn sysUserPlantConn : userPlantConnList) {
                QueryWrapper<TPlants> queryWrapper9 = new QueryWrapper<>();
                queryWrapper9.eq("ID", sysUserPlantConn.getPlantId());
                queryWrapper9.eq("DEL_FLAG",0);
                TPlants tPlants = iTPlantsService.getOne(queryWrapper9);
                if (tPlants == null) {
                    continue;
                }
                Map map1 = new HashMap();
                map1.put("plantId", tPlants.getId());
                map1.put("plantName", tPlants.getPlantFullName());
                plantNameList.add(map1);
            }
            loginInfo.put("plantNameList", plantNameList);

            szResult.setCode(200);
            szResult.setResult(loginInfo);
            szResult.setMsg("success");
            // sysLogBu.logRecord("网页端用户登录",sysUser.getTrueName(),"登录成功->ip:"+ip, plantId);
            sysLogBu.loginRecord(sysUser.getId(), ip);
        } else {
            szResult.setCode(200);
            szResult.setMsg("error");
            szResult.setResult("用户名或密码错误");
            // sysLogBu.logRecord("网页端用户登录",username,"登录失败,用户名或密码错误->ip:"+ip, plantId);
        }
        return szResult;
    }

    //    退出登录
    public SzResult logout(String token) {
        SzResult szResult = new SzResult();
        StpUtil.logout(token);
        szResult.setCode(200);
        szResult.setMsg("success");
        szResult.setResult("退出成功");
        return szResult;
    }

    //查询登录日志
    public SzResult loginLog(String user, String startTime, String endTime, String loginType,String page,String pageSize) {
        Page<SysLoginlog> page1 = new Page<>(Integer.parseInt(page), Integer.parseInt(pageSize));
        QueryWrapper<SysLoginlog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(loginType != null && !loginType.isEmpty(), "LOGIN_TYPE", loginType);//日志类型
        queryWrapper.between(startTime != null && !startTime.isEmpty() && endTime != null && !endTime.isEmpty(), "LOGIN_TIME", startTime, endTime);
        QueryWrapper<SysUser> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.and(i -> i.like("USER_NAME", user).or().like("TRUE_NAME", user).or().like("PHONE", user).or().like("USER_DESC", user));
        queryWrapper1.select("ID");
        List<SysUser> list1 = iSysUserService.list(queryWrapper1);
        List<String> userIdList = new ArrayList<>();
        for (SysUser sysUser : list1) {
            userIdList.add(sysUser.getId());
        }
        queryWrapper.in(!list1.isEmpty(), "USER_ID", userIdList);
        queryWrapper.orderByDesc("LOGIN_TIME");
        IPage<SysLoginlog> iPage = iSysLoginlogService.page(page1, queryWrapper);
        List<SysLoginlog> list = iPage.getRecords();
        List<SysLoginlogVo> listVo = new ArrayList<>();
        for (SysLoginlog sysLoginlog : list) {
            SysLoginlogVo sysLoginlogVo = new SysLoginlogVo();
            sysLoginlogVo.setId(sysLoginlog.getId());
            sysLoginlogVo.setLoginTime(sysLoginlog.getLoginTime());
            sysLoginlogVo.setLoginType(sysLoginlog.getLoginType());
            sysLoginlogVo.setLoginIp(sysLoginlog.getLoginIp());
            sysLoginlogVo.setUserId(sysLoginlog.getUserId());
            QueryWrapper<SysUser> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("ID", sysLoginlog.getUserId());
            SysUser sysUser = iSysUserService.getOne(queryWrapper2);
            sysLoginlogVo.setName(sysUser.getTrueName());
            listVo.add(sysLoginlogVo);
        }
        Long total = iPage.getTotal();
        Map<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("list", listVo);
        return SzResult.success(map);
    }
}
